<?

//	*******************************************
//	SbSE db connection module v1.2 / 2012.06.15
//	*******************************************

@include_once E.'_lib/_dbconfig.php';
if (!defined('DBProto')) return diags('No db configured');

switch (DBProto) {

	case 'oci8':
		define('USE_ADODB', 1);			// comment the whole line to disable it
		define('USE_ADODB_OCI', 1);	// comment the whole line to disable it
		define('TAS', ' ');	// table aliasing connector
		break;
		
	case 'mysql':
		define('TAS', ' as ');	// table aliasing connector
		break;
}

$DBCharset = 'utf8';

function tb($table) { 
	if (!T) return $table;
	
	$t = explode(',', $table);

	foreach($t as $k => $v) {
		$one = trim($v);
		
		if (sizeof($tx = explode(' ', $one)) == 2)
			$t[$k] = T.$tx[0].TAS.$tx[1];
		else
			$t[$k] = T.$one.TAS.$one; 
	}

	return implode(', ', $t);
}

function dbAnd() { 
	if (func_num_args()) {
		$a = func_get_args();
		switch(DBProto) {
			case 'oci8': return 'bitand('.implode(',', $a).')'; break;
			default: return implode(' & ', $a); break;
		}
	} else return '';
}

function dbAndS($a1, $a2) {	// return statement "all bits set in $a2 are set in $a1 too"
	switch(DBProto) {
		case 'oci8': return "bitand($a1,$a2)=$a2"; break;
		default: return "$a1 & $a2 = $a2"; break;
	}
}

function dbAndL($a1, $a2) {	// return statement "some bit set in $a2 is set in $a1 too"
	switch(DBProto) {
		case 'oci8': return "bitand($a1,$a2)!=0"; break;
		default: return "$a1 & $a2"; break;
	}
}

function dbAndI($a1, $a2) {	// return statement "any bit set in $a2 is NOT set in $a1"
	switch(DBProto) {
		case 'oci8': return "bitand($a1,$a2)=0"; break;
		default: return "!($a1 & $a2)"; break;
	}
}

function dbOr() {
	if (func_num_args()) {
		$a = func_get_args();
		switch(DBProto) {
			case 'oci8': return implode('+', $a).'-bitand('.implode(',', $a).')'; break;
			default: return implode(' | ', $a); break;
		}
	} else return '';
}
	

if (defined('USE_ADODB')) {
	require_once('_lib/adodb5/adodb.inc.php');
	$GLOBALS['db'] = NewADOConnection(DBProto);
	$GLOBALS['db']->charSet = 'AL32UTF8';
	
	if (!$GLOBALS['db']->PConnect($DBHost, $DBLogin, $DBPassword, $DBName))
		return diags("No db connection");

//dbdebug();
//$GLOBALS['db']->debug = true;

} else {
	require_once E.'_lib/_sql.php';
	if ($Link = @mysql_connect($DBHost, $DBLogin, $DBPassword)) {
		if (@mysql_select_db($DBName, $Link))
	@mysql_query("SET NAMES $DBCharset");
		else 
			return diags ("Can't select db");
	} else 
 		return diags("No db connection");
}


unset($DBHost);
unset($DBLogin);
unset($DBPassword);
unset($DBName);

return true;